package com.kust.smarthome.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kust.smarthome.web.mapper.DeviceStateMapper;
import com.kust.smarthome.web.mapper.DoorMapper;
import com.kust.smarthome.web.model.DeviceState;
import com.kust.smarthome.web.model.Door;
import com.kust.smarthome.web.service.IDoorService;
import com.kust.smarthome.web.vo.DeviceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author iAuzre
 * @since 2021-06-28
 */
@Service
public class DoorServiceImpl extends ServiceImpl<DoorMapper, Door> implements IDoorService {

    @Autowired
    private DoorMapper doorMapper;

    @Autowired
    private DeviceStateMapper deviceStateMapper;

    @Override
    public List<Door> getByUserId(Integer userId) {
        QueryWrapper<Door> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        return doorMapper.selectList(query);
    }

    @Override
    public List<Door> add(Integer userId, DeviceVo deviceVo) {
        QueryWrapper<Door> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        List<Door> list = doorMapper.selectList(query);

        LocalDateTime now = LocalDateTime.now();
        if (list.size() < 3) {
            Door door = new Door()
                    .setId(deviceVo.getId())
                    .setUrl("")
                    .setContent("这是一把门锁")
                    .setState(0)
                    .setCreated(now)
                    .setUserId(userId)
                    .setPassword("123456")
                    .setRoomId(deviceVo.getRoomId());
            doorMapper.insert(door);
            list.add(door);

            DeviceState deviceState = new DeviceState()
                    .setDeviceId(deviceVo.getId())
                    .setTypeId(3)
                    .setIsUpdate(0);

            deviceStateMapper.insert(deviceState);

            return list;
        }


        return list;
    }

    @Override
    public String updatePassword(Integer userId, Integer id, String password) {
        return null;
    }


}
